#include <QCoreApplication>

#include <QFile>
#include <QDebug>
#include <QtXml/qdom.h>
#include <QList>
#include "SmallBlock.h"
#include "BigBlock.h"
#include "Sudoku.h"
#include "Assumption.h"
#include <fstream>
#include <QDir>
#include <QTime>
#include "Tree.h"



using namespace std ;






int solveSudoku( QString pathToDir, QString filename )
{
    QFile file( pathToDir + '/' + filename ) ;


    //Open file for read
    if( !file.open( QIODevice::ReadOnly ) ) {
        qDebug() << "Not can read File! " << file.objectName() ;
        return 1 ;
    }

    //Push conetent of file to XML document
    QDomDocument document ;
    if( !document.setContent( &file ) ) {
        qDebug() << "Not can push file to content!" << endl ;
        return 1 ;
    }

    QDomElement root = document.documentElement() ;

    Sudoku* sudoku = Sudoku::readSudoku( root ) ;
    file.close() ;

    //Write begin state
    QString pathToBegin( pathToDir + '/' + "Begin_" + filename.remove( 4, filename.length()-4 ) + ".txt") ;
    ofstream beginOut( pathToBegin.toStdString().c_str() ) ;
    sudoku->print( beginOut ) ;
    beginOut.close() ;


    QTime time ;
    time.start() ;

    Tree tree( sudoku ) ;
    tree.start() ;

    int ms = time.elapsed() ;
    cout << "Number of node in tree: " << tree.getCounter() << endl ;


    //std::cout << "Sudoku check rules=" << sudoku->checkSudoku() << std::endl ;
    std::cout << "Time of work: " << ms << "msec" << std::endl ;

    //Write results to file
    QString pathToResults( pathToDir + '/' + "Result_" + filename.remove( 4, filename.length()-4 ) + ".txt") ;
    ofstream endOut( pathToResults.toStdString().c_str() ) ;
    sudoku->print( endOut ) ;
    endOut.close() ;

    delete sudoku ;
    return 0 ;
}


int main( /*int argc, char** argv*/ )
{
    std::cout << "PROGRAM STARTED" << std::endl ;


    QString pathToDir( "XMLs" ) ;
    QDir dir( pathToDir ) ;
    QStringList stringList = dir.entryList( QStringList("*.xml") ) ;
    foreach( QString filename, stringList )
    {
        std::cout << "Handle " << filename.toStdString() << std::endl ;
        solveSudoku( pathToDir, filename ) ;
        std::cout << "############################" << std::endl ;
        //system( "pause" ) ;
    }



    std::cout << "PROGRAM FINISHED" << std::endl ;
    system( "pause" ) ;
    return 0 ;
}
